<template>
  <div class="hs-table-cell">
    <div
      v-if="!promiseFulfilled"
      v-loading="true"
      style="width: 100%; height: 100%"
      class="hs-table-cell__promise"
    ></div>
    <hs-tag v-else-if="props.cellType === 'tag'" :type="cellValue.type">
      {{ cellValue.text }}</hs-tag
    >
    <span style="white-space: nowrap" v-else>{{ cellValue }}</span>
  </div>
</template>

<script setup>
import { ref, watchEffect } from 'vue'
import HsTag from '../Tag/Tag.vue'
import { codeToText } from 'element-china-area-data'
const emit = defineEmits()
const props = defineProps({
  cellType: {
    type: String,
  },
  row: {
    type: Object,
    required: true,
  },
  column: {
    type: Object,
    required: true,
  },
})
const promiseFulfilled = ref(true)
const getCellValue = async () => {
  const fieldName = props.column.property
  const value = props.row?.[fieldName] || '-'
  if (Object.prototype.toString.call(value) === '[object Promise]') {
    promiseFulfilled.value = false
    const res = await value.catch(() => {})
    promiseFulfilled.value = true
    return res || '-'
  }
  if (props.cellType === 'address') {
    const addressArr = value.split('/')
    const detail = addressArr.pop()
    return addressArr.map((code) => codeToText[code]).join('/') + ' ' + detail
  } else {
    return value
  }
}

let cellValue = ref('')
watchEffect(async () => {
  cellValue.value = await getCellValue()
})
</script>

<style lang="scss">
.hs-table-cell {
  height: 100%;
  width: 100%;
  text-overflow: inherit;
  overflow-wrap: inherit;
  overflow: inherit;
  &__promise {
    .el-loading-mask {
      display: flex;
      align-items: center;
      background-color: transparent;
    }
    .el-loading-spinner {
      text-align: start;
      margin: 0;
      position: unset;
      display: flex;
      align-items: center;
    }
    .circular {
      width: 24px;
      height: 24px;
    }
  }
}
</style>
